<template>
  <div class="main_box" v-loading="loading" style="padding-right: 10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.modelId ? '编辑服务模板' : '新增服务模板' }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item label="服务模板名称" prop="modelName">
            <el-input v-model="dataForm.modelName" @keydown.native="keydown($event)"></el-input>
          </el-form-item>
          <el-form-item prop="defaultFlag" label="模板类型">
            <el-radio-group v-model="dataForm.modelType">
              <el-radio :label="1">常规版</el-radio>
              <el-radio :label="2">自由版</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="地区" prop="streetIds">
            <Region ref="region" :streetValues="dataForm.streetIds" @regionChange="handleItemChange"
              :isChangeOnSelect="true"></Region>
          </el-form-item>
          <el-form-item label="小区" prop="villageId">
            <el-select v-model="dataForm.villageId" @change="handleVillageChange" @focus="handleVillageFocus" clearable
              filterable>
              <el-option v-for="item in villageList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="按键样式模板">
            <el-select v-model="dataForm.btnModelId" clearable filterable @change="handleBtnModelChange">
              <el-option v-for="item in btnModelList" :label="item.modelName" :value="item.modelId"
                :key="item.modelId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="支持语音下单">
            <el-radio v-model="dataForm.btnVoiceFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.btnVoiceFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item label="模板背景颜色">
            <el-input class="color-input" v-model="dataForm.bgColor" clearable filterable
              placeholder="输入或者选择HEX颜色，例:#409EFF">
              <el-color-picker slot="append" v-model="dataForm.bgColor"></el-color-picker>
            </el-input>
          </el-form-item>
          <el-form-item label="精选是否采用新的样式" prop="btnStyle">
            <el-radio-group v-model="dataForm.btnStyle">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item prop="remark" label="备注">
            <el-input type="textarea" v-model="dataForm.remark"></el-input>
          </el-form-item>
          <el-form-item prop="defaultFlag" label="是否默认模板">
            <el-radio-group v-model="dataForm.defaultFlag">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="关联补贴金类型" width="300" align="center">
                <el-select v-model="dataForm.relationAmountType" multiple placeholder="请选择">
                  <el-option key="1" label="养老金" value="1">
                  </el-option>
                  <el-option key="2" label="物业金" value="2">
                  </el-option>
                </el-select>
            </el-form-item>
        </el-row>

        <el-row style="width: max-content; max-width: calc(100vw - 280px)">
          <div class="tit">
            <h2>服务功能键信息</h2>
            <el-button icon="el-icon-plus" type="success" plain size="medium" circle @click="addBtn"> </el-button>
          </div>
          <el-table max-height="600" :data="dataForm.serverModelBtns" style="margin-top: 20px">
            <el-table-column label="操作" width="60" align="center" fixed>
              <template slot-scope="scope">
                <el-button icon="el-icon-minus" type="danger" plain size="medium" @click="subBtn(scope.$index)" circle>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="功能键编号" width="100" align="center" fixed>
              <template slot-scope="scope">
                <el-input type="number" v-model.trim="scope.row.btnCode" clearable filterable
                  @input="handleServerCodeInput(scope.$index, scope.row.btnCode)"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="服务功能键" width="200" align="center" fixed>
              <template slot-scope="scope">
                <el-select v-model="scope.row.btnId" @focus="getServerBtnList(scope.row.btnId)" clearable filterable>
                  <el-option v-for="item in serverBtnList" :label="item.name" :value="item.id" :key="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="自定义功能键图片" width="180" align="center">
              <template slot-scope="scope">
                <div class="add-img" v-if="!scope.row.customImage" @click="handleSelectImg(scope.$index)">
                  <span class="el-icon-plus"></span>
                </div>
                <el-image @click.native="handleSelectImg(scope.$index)" fit="cover" :src="scope.row.customImage"
                  v-else></el-image>
              </template>
            </el-table-column>
            <el-table-column label="自定义功能键名称" width="130" align="center">
              <template slot-scope="{ row }">
                <el-input v-model="row.customName"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="功能键描述" width="220" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.describes"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="按键归类" width="220" align="center" v-if="dataForm.modelType == 1">
              <template slot-scope="scope">
                <el-cascader v-model="scope.row.moduleCodes" clearable filterable :options="btnMRelationList" :props="{
                  children: 'btnFormats',
                  value: 'code',
                  label: 'name',
                }"></el-cascader>
              </template>
            </el-table-column>
            <el-table-column label="关联类型" width="200" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.relationType" @change="handleRelationTypeChange(scope.row)">
                  <el-option v-for="item in $Options.relationTypeList" :label="item.name" :value="item.id" :key="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="事件类型" width="230" align="center">
              <template slot-scope="scope">
                <el-select v-show="showColumn(scope.row, 1)" @change="handleEventChange(scope.row)"
                  v-model="scope.row.eventId" placeholder="请选择事件">
                  <el-option v-for="item in getEventList(scope.row)" :value="item.id" :label="item.name" :key="item.id">
                  </el-option>
                </el-select>
                <span v-show="!showColumn(scope.row, 1)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="关联内容" width="350" align="center">
              <template slot-scope="scope">
                <template v-if="showColumn(scope.row, 2)">
                  <el-cascader v-if="scope.row.eventId == 7" style="width: 100%" filterable clearable
                    v-model="scope.row.linkUrl" :options="residentAddressList"
                    :props="{ value: 'id', label: 'name', checkStrictly: true }" placeholder="请选择栋单元层">
                  </el-cascader>
                  <el-select v-else-if="scope.row.eventId == 51" style="width: 100%" v-model="scope.row.linkUrl"
                    placeholder="请选择模板">
                    <el-option v-for="item in serverModelList" :value="item.modelId" :label="item.modelName"
                      :key="item.modelId"></el-option>
                  </el-select>
                  <el-select v-else-if="scope.row.eventId === 55" style="width: 100%" v-model="scope.row.linkUrl"
                    placeholder="请选择设备类型">
                    <el-option v-for="item in $Options.equipmentType" :value="item.key" :label="item.value"
                      :key="item.key" />
                  </el-select>
                  <el-select v-else-if="scope.row.eventId == 57" style="width: 100%" v-model="scope.row.linkUrl"
                    placeholder="请选择内容">
                    <el-option :value="1" label="物业"></el-option>
                    <el-option :value="2" label="用户"></el-option>
                  </el-select>
                  <el-input v-else v-model="scope.row.linkUrl"
                    :placeholder="scope.row.eventId == 52 ? '电话号码/内容' : '请输入关联内容'"> </el-input>
                </template>
                <span v-else="!showColumn(scope.row, 2)"> # </span>
              </template>
            </el-table-column>

            <el-table-column label="服务分类" width="300" align="center">
              <template slot-scope="scope">
                <!-- <el-select
                  v-show="showColumn(scope.row, 3)"
                  placeholder="请选择服务分类"
                  v-model="scope.row.classifyIds"
                  style="width: 280px"
                  multiple
                  clearable
                  filterable
                  @change="handleServerClassifyChange(scope.row, scope.$index)"
                >
                  <el-option v-for="item in serverClassifyList" :key="item.name" :label="item.name" :value="item.id"> </el-option>
                </el-select> -->
                <el-cascader filterable @change="handleServerClassifyChange(scope.row, scope.$index)"
                  v-show="showColumn(scope.row, 3)" v-model="scope.row.classifyIds" placeholder="请选择服务分类"
                  :options="serverClassifyList" :props="{ multiple: true, value: 'id', label: 'name', emitPath: false }"
                  clearable :show-all-levels="false"></el-cascader>
                <span v-show="!showColumn(scope.row, 3)"> # </span>
              </template>
            </el-table-column>

            <el-table-column label="商户" width="300" align="center" v-if="dataForm.modelType == 1">
              <template slot-scope="scope">
                <el-select v-show="showColumn(scope.row, 4)" style="width: 280px" placeholder="请选择商户"
                  v-model="scope.row.businessIds" multiple clearable filterable
                  @change="handleBusinessChange(scope.row, scope.$index)"
                  @focus="handleBusinessFocus(scope.row, scope.$index)">
                  <el-option v-for="item in scope.row.businessList" :key="item.name" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
                <span v-show="!showColumn(scope.row, 4)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="仅会员购买" align="center" width="200">
              <template slot-scope="scope">
                <el-switch v-show="showColumn(scope.row, 5)" v-model="scope.row.limitType" :active-value="1"
                  :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
                <span v-show="!showColumn(scope.row, 5)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="支持语音下单" align="center" width="200">
              <template slot-scope="scope">
                <el-switch v-show="showColumn(scope.row, 6)" v-model="scope.row.voiceOrderFlag" :active-value="1"
                  :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
                <span v-show="!showColumn(scope.row, 6)"> # </span>
              </template>
            </el-table-column>
            <el-table-column label="服务时间范围" width="300" align="center">
              <template slot-scope="{ row }">
                <div class="server-time-range"
                  v-if="row.eventId !== 55 && row.eventId !== 57 && row.eventId !== 58 && row.eventId !== 59 && row.eventId !== 60 && row.eventId !== 61">
                  <el-time-picker placeholder="开始时间" v-model="row.beginServerTime" value-format="HH:mm"
                    format="HH:mm"></el-time-picker>
                  <span class="separate"></span>
                  <el-time-picker placeholder="结束时间" v-model="row.endServerTime" value-format="HH:mm"
                    format="HH:mm"></el-time-picker>
                </div>
                <span v-else>#</span>
              </template>
            </el-table-column>
            <el-table-column label="合并功能键编号" align="center" width="130px">
              <template slot-scope="{ row }">
                <span
                  v-if="row.eventId == 6 || row.eventId === 55 || row.eventId === 56 || row.eventId == 57 || row.eventId == 58 || row.eventId == 60">#</span>
                <el-input v-else v-model="row.parentBtnCode"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" v-if="dataForm.modelType == 1" width="100">
              <template slot-scope="scope">
                <div v-show="showColumn(scope.row, 4)">
                  <el-button plain type="mini" @click.native="handleOperateMore(scope.row, scope.$index)">编辑</el-button>
                </div>
                <span v-show="!showColumn(scope.row, 4)"> # </span>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row type="flex" justify="center">
<!--          <el-button v-if="userRole == 1 && detailRole == 1" plain type="success"
            @click="sureClick(1)">保存并一键同步</el-button>-->
          <el-button plain type="primary" @click="sureClick(0)">保 存</el-button>
          <el-button plain @click="returnList">取 消</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 产品选择器 -->
    <server-select ref="ServerSelect" @saveServerData="saveServerData"></server-select>

    <!-- 图片选择 -->
    <ImageSelect fileType="1" :show="imageSelect.show" :limit="1" @cancel="imageSelect.show = false"
      @getUrlList="getUrlList"></ImageSelect>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import ServerTemplateApi from '@/api/server/serverTemplate';
import VillageApi from '@/api/address/village';
import VillageAreaApi from '@/api/address/villageArea';
import BusinessApi from '@/api/business/business';
import GoodsApi from '@/api/goods/goods';
import ServerClassifyApi from '@/api/server/serverClassify';
import ServerBtnApi from '@/api/server/serverBtn';
import BtnModelApi from '@/api/operation/btnModel';
import Region from '@/components/Region';
import ServerSelect from '@/components/ServerSelect';
import ImageSelect from '@/components/ImageSelect.vue';
import UploadImg from '../../components/UploadImg.vue';
import { getStorage } from '@/utils/auth';
import { USER_INFO } from '@/constants/storeName';
import importExcel from '@/excel/importExcel';
import { Message } from 'element-ui';
export default {
  name: 'ServerTemplateAdd',
  data() {
    return {
      isCopy: this.$route.query.isCopy || 0,
      dataForm: {
        relationAmountType:[],
        modelId: '',
        modelName: '',
        modelType: 1,
        defaultFlag: 0,
        villageId: '',
        villageName: '',
        streetIds: [],
        provinceId: '',
        provinceName: '',
        cityId: '',
        cityName: '',
        areaId: '',
        areaName: '',
        streetId: '',
        streetName: '',
        update: '', // 保存并一键同步保存值为1，普通的保存就不传这个值
        serverModelBtns: [
          //服务信息列表
          // {
          //     btnCode:"",
          //     btnId:"",
          //     relationType:"", //案件类型 1.产品 2.H5连接 3.小程序连接
          //     linkUrl:"",
          //     describe:"",
          //     moduleCodes:[],
          //     classifyIds:"",
          //     classifyList:"", // 发送请求的时候去掉
          //     businessIds:"",   //发送请求的时候去掉
          //     businessList:[], //商品列表放在这里，发送请求的时候过滤掉
          //     parentBtnCode:"",
          //     btnGoodsParams:[] //服务选择弹框的表格数据
          // }
        ],
        btnVoiceFlag: 1,
        btnModelId: '',
        bgColor: '',
        btnStyle: 0,
        remark: '',
      },
      roleRules: {
        modelName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
          { max: 50, message: '长度不超过50个字', trigger: 'blur' },
        ],
      },
      userRole: '',
      detailRole: '',
      villageList: [], //小区列表
      serverBtnList: [], //服务功能键列表
      serverClassifyList: [], //二级分类列表
      loading: false,
      allEventList: [],
      imageSelect: {
        show: false,
        index: '',
      },
      btnModelList: [],
      btnMRelationList: [],
      residentAddressList: [],
      serverModelList: [],
    };
  },
  mounted() {
    this.init();
  },
  watch: {
    'dataForm.modelType': {
      handler(val) {
        const { serverModelBtns } = this.dataForm;
        if (val == 1) {
          this.allEventList['5'] = [
            { id: 3, name: '资讯' },
            { id: 4, name: '聊天' },
            { id: 5, name: '活动报名' },
          ];
        } else if (val == 2) {
          this.allEventList['5'] = [
            { id: 3, name: '资讯' },
            { id: 4, name: '聊天' },
          ];
          serverModelBtns.forEach((item) => {
            item.relationType == 5 && item.eventId == 5 && item.eventId == '';
            item.relationType == 1 && (item.eventId = 10);
          });
        }
      },
    },
  },
  activated() { },
  components: {
    Region,
    ServerSelect,
    ImageSelect,
    UploadImg,
  },
  methods: {
    async init() {
      // 获取用户角色
      this.userRole = getStorage(USER_INFO).userRole;
      this.detailRole = getStorage(USER_INFO).detailRole;

      // 获取全部的事件,这里会修改事件，所以不能直接使用eventListMap
      this.allEventList = this.$Options.eventListMap;

      // 按键样式列表
      await this.getBtnModelList();
      // // 获取全部的二级服务分类列表
      this.getServerClassifyList();
      if (this.$route.query.id) {
        this.dataForm.modelId = this.$route.query.id;
        this.getData();
      } else {
        // 获取服务功能键列表
        this.initServerBtnList();
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    async getData() {
      const { data } = await ServerTemplateApi.getServerTemplateInfo({
        id: this.dataForm.modelId,
      });
      data.relationAmountType = data.relationAmountType?data.relationAmountType.split(','):[]
      this.$Utils.bindingBean(this.dataForm, data);
      // 一些值需要修改然后赋值给dataFrom
      let serverModelBtns = [];
      if (data.serverModelBtns) {
        serverModelBtns = data.serverModelBtns.map((item) => {
          let linkUrl = item.linkUrl;
          if (linkUrl) {
            if (item.eventId == 7) {
              linkUrl = item.linkUrl.split(',').map((item2) => Number(item2));
            } else if (item.eventId == 51) {
              linkUrl = Number(item.linkUrl);
            }
          }
          item.serverTimeRange && (item.serverTimeRange = item.serverTimeRange.split(','));
          return {
            modelId: item.modelId,
            btnCode: item.btnCode,
            moduleCodes: [item.moduleCode, item.formatCode].filter((item) => item),
            describes: item.describes,
            customImage: item.customImage,
            customName: item.customName,
            btnId: item.btnId ? item.btnId : '',
            relationType: item.relationType,
            linkUrl,
            voiceOrderFlag: item.voiceOrderFlag,
            eventId: item.eventId,
            classifyIds: item.classifyIdList,
            businessIds: item.businessList ? item.businessList.map((item2) => item2.id) : [],
            businessList: item.businessList,
            parentBtnCode: item.parentBtnCode,
            limitType: item.limitType,
            btnGoodsParams: item.btnGoodsParams,
            beginServerTime: item.serverTimeRange ? item.serverTimeRange[0] : '',
            endServerTime: item.serverTimeRange ? item.serverTimeRange[1] : '',
            residentAddress: [item.buildId, item.unitId, item.floorId].filter((item) => item),
          };
        });
      }
      if (data.btnModelId) {
        // 存在按键样式模板
        this.btnMRelationList = this.btnModelList.find((item) => item.modelId == data.btnModelId).btnModelRelations;
        this.formatBtnMRelationList();
      }
      this.dataForm.serverModelBtns = serverModelBtns;
      this.dataForm.streetIds = [data.provinceId, data.provinceName, data.cityId, data.cityName, data.areaId, data.areaName, data.streetId, data.streetName];

      this.villageList = [{ id: data.villageId, name: data.villageName }];
      this.getModelList();
      this.getResidentAddressList();
      // 获取服务功能键列表
      this.dataForm.modelType = data.modelType;
      this.initServerBtnList();
    },

    saveServerData(obj) {
      this.dataForm.serverModelBtns[obj.index].btnGoodsParams = obj.tableData.filter((item) => item.serverNo);
    },
    // 获取按键样式模板列表
    async getBtnModelList() {
      const { data } = await BtnModelApi.btnModelList();
      this.btnModelList = data || [];
    },
    handleBtnModelChange() {
      const { btnModelId, serverModelBtns } = this.dataForm;
      serverModelBtns.forEach((item) => (item.moduleCodes = []));
      if (btnModelId) {
        this.btnMRelationList = this.btnModelList.find((item) => btnModelId == item.modelId).btnModelRelations;
        this.formatBtnMRelationList();
      } else {
        this.btnMRelationList = [];
      }
    },
    formatBtnMRelationList() {
      // this.btnMRelationList.sort((a,b)=>a.sort-b.sort)
      this.btnMRelationList.forEach((item, index) => {
        if (item.btnFormats && item.btnFormats.length) {
          // item.btnFormats.sort((a,b)=>a.sort-b.sort)
          item.btnFormats.forEach((item2) => {
            this.$set(item2, 'code', item2.formatCode);
            this.$set(item2, 'name', `${item2.row}行${item2.col}列`);
          });
        }
        this.$set(item, 'code', item.moduleCode);
        this.$set(item, 'name', `${this.$Filters.formatModuleType(item.moduleType)}模块`);
      });
    },
    // 关联类型改变,全部要清空
    handleRelationTypeChange(row) {
      row.eventId = '';
      row.linkUrl = '';
      row.voiceOrderFlag = 0;
      row.classifyIds = [];
      row.businessIds = [];
      row.btnGoodsParams = [];
      row.businessIdList = [];
    },
    // 事件全部改变
    handleEventChange(row) {
      row.linkUrl = '';
      row.voiceOrderFlag = 0;
      row.classifyIds = [];
      row.businessIdList = [];
      row.btnGoodsParams = [];
      row.businessIdList = [];
    },
    /**
     * 根据关联类型来判断是否显示这一列
     * @param type 1表示事件类型 2表示关联内容 3表示服务分类 4表示商户、操作
     */

    showColumn(row, type) {
      const { relationType, eventId } = row;
      console.log(eventId);
      switch (type) {
        case 1:
          return relationType == 1 || relationType == 4 || relationType == 5;
        case 2:
          return relationType == 1 || relationType == 2 || relationType == 3 || eventId == 2 || eventId == 7 || eventId == 51 || eventId == 52 || eventId == 54 || eventId === 55 || eventId === 57;
        case 3:
          return relationType == 1 || eventId == 3 || eventId == 5 || eventId == 7 || eventId == 60;
        case 4:
          return (relationType == 1 || eventId !== 56) && eventId !== 55 && eventId !== 57 && eventId !== 58 && eventId !== 59 && row.eventId !== 61;
        case 5:
          return relationType == 1;
        case 6:
          return eventId == 10 || eventId == 18 || eventId == 19;
      }
    },
    // 选择图片
    handleSelectImg(index) {
      this.imageSelect.show = true;
      this.imageSelect.index = index;
    },
    getUrlList([val]) {
      const {
        imageSelect,
        dataForm: { serverModelBtns },
      } = this;
      imageSelect.show = false;
      console.log(val);
      serverModelBtns[imageSelect.index].customImage = val.url;
    },
    // 获取服务分类列表
    getEventList(row) {
      console.log(this.allEventList[row.relationType]);
      return this.allEventList[row.relationType];
    },
    addBtn() {
      let arr = [];
      let btnCode = 0;
      this.dataForm.serverModelBtns.forEach((item) => {
        if (item.btnCode) {
          arr.push(Number(item.btnCode));
        }
      });
      arr.sort((a, b) => a - b);

      while (true) {
        btnCode++;
        if (btnCode != arr[btnCode - 1]) {
          break;
        }
      }

      this.dataForm.serverModelBtns.push({
        btnCode: String(btnCode),
        describes: '',
        customImage: '',
        customName: '',
        btnId: '',
        relationType: 1,
        linkUrl: '',
        voiceOrderFlag: 0,
        eventId: 10,
        classifyIds: [],
        businessIds: [],
        businessList: [],
        btnGoodsParams: [],
        parentBtnCode: '',
        limitType: 0,
        beginServerTime: '',
        endServerTime: '',
        moduleCodes: [],
      });
    },
    subBtn(index) {
      this.dataForm.serverModelBtns.splice(index, 1);
    },
    // 获取产品分类列表
    getServerClassifyList() {
      let param = { level: -2 }
      ServerClassifyApi.listServerClassifyTree(param).then(res => {
        this.serverClassifyList = res.data
      })
    },
    // 获取服务功能键列表
    initServerBtnList() {
      let params = { btnType: this.dataForm.modelType };
      ServerBtnApi.serverBtnList(params).then((res) => {
        this.serverBtnList = res.data;
      });
    },
    getServerBtnList(id) {
      let params = { btnType: this.dataForm.modelType };
      let filterIds = this.dataForm.serverModelBtns
        .filter((item) => item.btnId && item.btnId != id)
        .map((item) => item.btnId)
        .join(',');
      if (filterIds) {
        params.filterIds = filterIds;
      }
      ServerBtnApi.serverBtnList(params).then((res) => {
        this.serverBtnList = res.data;
      });
    },
    // 点击编辑操作弹框数据
    handleOperateMore(row, index) {
      if (row.businessIds.length == 0) {
        this.$message.warning('请先填服务分类和商户');
        return;
      }
      let serverBtnParam = this.dataForm.serverModelBtns[index].btnGoodsParams;
      let params = {
        classifyIds: row.classifyIds.join(','),
        businessIds: row.businessIds.join(','),
        modelId: this.dataForm.modelId ? this.dataForm.modelId : null,
        btnId: this.dataForm.serverModelBtns[index].btnId,
        villageId: this.dataForm.villageId,
        provinceId: this.dataForm.provinceId,
        cityId: this.dataForm.cityId,
        areaId: this.dataForm.areaId,
        name: '',
        parentBtnCode: row.parentBtnCode,
      };
      if (this.$Hooks.isDockingEvent(row.eventId)) {
        params.dockingFlag = 2;
        params.dockingType = params.dockingType = row.eventId == 18 ? 1 : row.eventId == 19 ? 2 : '';
      }
      let moduleType = '';
      if (row.moduleCodes[0]) {
        moduleType = this.btnMRelationList.find((item) => item.moduleCode == row.moduleCodes[0]).moduleType;
      }
      this.$refs.ServerSelect.showDialog({
        params,
        moduleType,
        serverBtnParam,
        index,
        businessList: row.businessList,
      });
    },
    // 服务分类选择框改变值的时候调用的函数
    handleServerClassifyChange(row, index) {
      this.dataForm.serverModelBtns[index].businessIds = [];
      this.dataForm.serverModelBtns[index].businessList = [];
      this.dataForm.serverModelBtns[index].btnGoodsParams = [];
    },

    // 商户选择框改变值的时候调用的函数
    handleBusinessChange(row, index) {
      let obj = this.dataForm.serverModelBtns[index];
      let businessList = this.dataForm.serverModelBtns[index].businessIds;
      obj.btnGoodsParams = (obj.btnGoodsParams || []).filter((item) => businessList.some((item2) => item.businessId == item2));
    },
    // 商户选择框点击聚焦的时候调用的函数
    handleBusinessFocus(row, index) {
      let params = {
        type: 2,
        serverClassifyIds: row.classifyIds.join(','),
        provinceId: this.dataForm.provinceId,
        cityId: this.dataForm.cityId,
        areaId: this.dataForm.areaId,
        villageId: this.dataForm.villageId,
      };
      if (params.serverClassifyIds.length > 0) {
        BusinessApi.listIdName(params).then((res) => {
          this.dataForm.serverModelBtns[index].businessList = res.data;
        });
      }
    },
    // 通过小区获取栋单元层下的数据
    async getResidentAddressList() {
      const { data } = await VillageAreaApi.getListTree({
        villageId: this.dataForm.villageId,
      });
      this.residentAddressList = data || [];
    },
    handleVillageChange() {
      this.residentAddressList = [];
      this.serverModelList = [];
      this.dataForm.serverModelBtns.forEach((item) => {
        item.businessIds = [];
        item.businessList = [];
        item.btnGoodsParams = [];
        (item.eventId == 7 || item.eventId == 51) && (item.linkUrl = '');
      });
      if (!this.dataForm.villageId) return;
      this.dataForm.villageName = this.villageList.find((item) => item.id == this.dataForm.villageId).name;
      this.getResidentAddressList();
      this.getModelList();
    },
    handleVillageFocus() {
      // 点击聚焦小区的时候才发送请求数据
      if (this.dataForm.streetIds.length > 0) {
        let param = {
          provinceId: this.dataForm.provinceId,
          cityId: this.dataForm.cityId,
          areaId: this.dataForm.areaId,
          streetId: this.dataForm.streetId,
          name: '',
        };
        VillageApi.villageList(param).then((res) => {
          this.villageList = res.data;
        });
      }
    },
    // 输入功能键编号的时候
    handleServerCodeInput(index, btnCode) {
      let reg = /^[1-9][0-9]*$/;

      if (reg.test(btnCode)) {
        this.dataForm.serverModelBtns[index].btnCode = btnCode;
      } else {
        this.dataForm.serverModelBtns[index].btnCode = '';
      }
    },

    handleItemChange(val) {
      // 地区改变要清空小区和设备地址还有列表
      this.dataForm.villageId = '';
      this.dataForm.villageName = '';
      this.villageList = [];
      this.residentAddressList = [];
      this.dataForm.serverModelBtns.forEach((item) => {
        item.businessIds = [];
        item.businessList = [];
        item.btnGoodsParams = [];
        item.residentAddress = null;
        item.eventId == 51 && (item.linkUrl = '');
      });
      this.dataForm.provinceId = val.provinceId;
      this.dataForm.provinceName = val.provinceName;
      this.dataForm.cityId = val.cityId;
      this.dataForm.cityName = val.cityName;
      this.dataForm.areaId = val.areaId;
      this.dataForm.areaName = val.areaName;
      this.dataForm.streetId = val.streetId;
      this.dataForm.streetName = val.streetName;
      if (val.provinceId) {
        this.dataForm.streetIds = [val.provinceId, val.cityId, val.areaId, val.streetId];
      } else {
        this.dataForm.streetIds = [];
      }
    },
    // handleVillageChange(){
    //   this.dataForm.villageId = ""
    //   this.dataForm.serverModelBtns.forEach(item=>item.eventId==51&&(item.linkUrl=""))
    //   this.getModelList()
    // },
    async getModelList() {
      const { villageId } = this.dataForm;
      if (!villageId) return [];
      // 发送请求
      const { data } = await ServerTemplateApi.listModel({
        villageId: this.dataForm.villageId,
      });
      console.log(data);
      this.serverModelList = data || [];
    },
    async sureClick(update) {
      this.dataForm.update = update; //决定选择哪个保存
      // 提交
      await this.$refs.dataForm.validate();
      let { serverModelBtns, modelType, btnStyle } = this.dataForm;

      let flag = false;
      flag = serverModelBtns.some((item, index) => {
        if (!item.btnCode) {
          this.$message.error('请填写功能键编号');
          return true;
        }

        if (serverModelBtns.findIndex((item2) => item.btnCode == item2.btnCode) != index) {
          this.$message.error('功能键编号重复');
          return true;
        }

        if (!item.btnId) {
          this.$message.error('请选择服务功能键');
          return true;
        }
        if ((item.beginServerTime && !item.endServerTime) || (!item.beginServerTime && item.endServerTime)) {
          // 如果服务开始时间或者结束时间只填写一个另外一个直接清空
          item.beginServerTime = '';
          item.endServerTime = '';
          return;
        }

        switch (item.relationType) {
          case 1:
            return !item.classifyIds.length || !item.eventId;
          case 2:
            return !item.linkUrl;
          case 3:
            return !item.linkUrl;
          case 4:
            return !item.eventId || ((item.eventId == 2 || item.eventId == 51 || item.eventId == 52) && !item.linkUrl);
          case 5:
            return !item.eventId || (item.eventId == 3 && !item.classifyIds.length) || (item.eventId == 5 && !item.classifyIds.length) || (item.eventId == 54 && !item.linkUrl);
        }
      });
      if (flag) {
        setTimeout(() => {
          this.$message.error('请完善服务信息');
        }, 1000);
        return;
      }
      if (modelType == 1) {
        // 常规版
        for (let i = 0; i < serverModelBtns.length; i++) {
          const btnCode = serverModelBtns[i].btnCode;
          const relationType = serverModelBtns[i].relationType;
          const businessIds = serverModelBtns[i].businessIds;
          if (relationType == 1) {
            if(serverModelBtns[i].btnGoodsParams==null){
              this.$message.error(`功能键编号为${btnCode}的没有编辑填写编号`);
              return;
            }
            if (!serverModelBtns[i].btnGoodsParams.some((item) => item.serverNo) ) {
              this.$message.error(`功能键编号为${btnCode}的没有编辑填写编号`);
              return;
            }
          
            if (!businessIds.length) {
              this.$message.error(`功能键编号为${btnCode}的没有选择商户`);
              return;
            }
          }

          if (relationType == 1 || serverModelBtns[i].eventId == 6) {
            serverModelBtns[i].eventId == 6 && (serverModelBtns[i].parentBtnCode = '');
            if (btnStyle && !serverModelBtns[i].parentBtnCode && (!serverModelBtns[i].moduleCodes || !serverModelBtns[i].moduleCodes.length)) {
              this.$message.error(`功能键编号为${btnCode}的没有选择按键归类`);
              return;
            }
          }
        }
      } else {
      }
      // 过滤的serverModelBtns里面的businessList、classifyIds、classifyList、businessIds
      this.serverModelBtns = serverModelBtns.map((item) => {
        const { relationType, eventId } = item;
        return {
          btnCode: item.btnCode,
          btnId: item.btnId,
          describes: item.describes,
          moduleCode: item.moduleCodes[0] || '',
          formatCode: item.moduleCodes[1] || '',
          customImage: item.customImage,
          customName: item.customName,
          relationType,
          linkUrl:
            (relationType == 1 || relationType == 2 || relationType == 3 || eventId == 2 || eventId == 7 || eventId == 51 || eventId == 52 || eventId == 54 || eventId === 55 || eventId === 57) && item.linkUrl
              ? item.linkUrl.toString()
              : '',
          voiceOrderFlag: item.eventId == 10 || item.eventId == 18 || item.eventId == 19 ? item.voiceOrderFlag : 0,
          eventId: relationType == 1 || relationType == 4 || relationType == 5 ? item.eventId : '',
          classifyIdList: relationType == 1 || (relationType == 5 && eventId == 3) || (relationType == 5 && eventId == 5) || (relationType == 5 && eventId == 7) || eventId === 60 ? item.classifyIds : [],
          businessIdList: relationType == 1 || (relationType == 5 && eventId == 7) || eventId === 60 ? item.businessIds : [],
          parentBtnCode: item.eventId == 6 ? '' : item.parentBtnCode,
          limitType: (relationType == 1) == 1 ? item.limitType : 0,
          serverTimeRange: item.beginServerTime ? item.beginServerTime + ',' + item.endServerTime : '',
          btnGoodsParams: relationType == 1 || eventId === 60 ? item.btnGoodsParams : [],
        };
      });
      await this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {});
      this.dataForm.modelId && this.isCopy == 0 ? this.editData() : this.addData();
    },
    editData() {
      // 编辑
      var cond = {
        modelId: this.dataForm.modelId,
        modelName: this.dataForm.modelName,
        relationAmountType:this.dataForm.relationAmountType.join(','),
        modelType: this.dataForm.modelType,
        defaultFlag: this.dataForm.defaultFlag,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        villageId: this.dataForm.villageId,
        villageName: this.dataForm.villageName,
        serverModelBtns: this.serverModelBtns,
        btnVoiceFlag: this.dataForm.btnVoiceFlag,
        btnModelId: this.dataForm.btnModelId,
        bgColor: this.dataForm.bgColor,
        btnStyle: this.dataForm.btnStyle,
        remark: this.remark,
      };
      if (this.dataForm.update) {
        cond.update = this.dataForm.update;
      }
      this.loading = true;
      ServerTemplateApi.editServerTemplate(cond)
        .then((data) => {
          this.$Utils.notifySuccess();
          this.returnList();
        })
        .catch((err) => {
          Message.closeAll();
          if (err.message.includes('timeout')) {
            this.$Utils.notifySuccess();
            this.returnList();
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    addData() {
      // 新增
      var cond = {
        modelName: this.dataForm.modelName,
        modelType: this.dataForm.modelType,
        defaultFlag: this.dataForm.defaultFlag,
        relationAmountType:this.dataForm.relationAmountType.join(','),
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        villageId: this.dataForm.villageId,
        villageName: this.dataForm.villageName,
        serverModelBtns: this.serverModelBtns,
        btnVoiceFlag: this.dataForm.btnVoiceFlag,
        btnModelId: this.dataForm.btnModelId,
        bgColor: this.dataForm.bgColor,
        btnStyle: this.dataForm.btnStyle,
        remark: this.remark,
      };
      if (this.dataForm.update) {
        cond.update = this.dataForm.update;
      }
      this.loading = true;
      ServerTemplateApi.addServerTemplate(cond)
        .then(() => {
          this.$Utils.notifySuccess();
          this.returnList();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    returnList() {
      // 返回上一界面
      this.$store.dispatch('delView', this.$route);
      this.$router.push({ path: '/server/serverTemplateManagement' });
    },
  },
};
</script>

<style lang="scss">
@import '@/assets/css/views/add.scss';
@import '@/assets/css/views/content.scss';
</style>
<style lang="scss" scoped>
.color-input {
  ::v-deep .el-input-group__append {
    border: none;
    line-height: 0;
    padding: 0;
    height: 30px;

    .el-color-picker {
      height: 30px;

      .el-color-picker__trigger {
        height: 30px;
        width: 30px;
      }
    }
  }
}

.server-time-range {
  display: flex;
  align-items: center;

  .separate {
    width: 20px;
    height: 1px;
    margin: 0 7px;
    background-color: gray;
  }
}

.add-img {
  width: 100px;
  height: 100px;
  border: 1px dotted #e5e5e5;
  border-radius: 10px;
  display: inline-flex;
  align-items: center;
  justify-content: space-around;
  cursor: pointer;

  .el-icon-plus {
    font-size: 30px;
    color: #e5e5e5;
  }

  .el-image {
    width: 120px;
    height: 120px;
  }
}
</style>
